package com.leyou.upload.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    private static final List<String> CONTENT_TYPES = Arrays.asList("image/png","image/jpeg","application/x-png","application/x-jpg");
    private static final Logger LOGGER= LoggerFactory.getLogger(UploadService.class);

    public String uploadImage(MultipartFile file) {
        String originalFilename = file.getOriginalFilename();


        //校验文件类型
        String contentType = file.getContentType();
        if(!CONTENT_TYPES.contains(contentType)){
            //打印后台日志内容，方便管理员查看问题
            LOGGER.info("文件类型不合法{}",originalFilename);
            return null;
        }

        //校验文件内容
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage==null){
                LOGGER.info("文件内容不合法:{}",originalFilename);
            }
            //上传到服务器
            file.transferTo(new File("C:\\Users\\Allen\\Documents\\1.BugoutProject3\\image\\"+originalFilename));
            //生成url地址，返回地址
            return "http://image.leyou.com/"+originalFilename;
        } catch (Exception e) {
            LOGGER.info("服务器内部错误！");
            e.printStackTrace();
        }
        return null;
    }
}
